var express = require('express');
var router = express.Router();
var mysql = require('mysql');

var db = mysql.createPool({ host: 'localhost', user: 'root', password: '', database: 'blog' });

router.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Headers", "token,sign");   //消息头自定义参数设置
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
})

router.get('/', function(req, res, next) {
    res.send('404')
})

router.get('/get', function(req, res, next) {
    var type = req.query.type || '';
    var page = req.query.page || 1;
    var where = ' WHERE category="' + type + '"'; //查询条件

    // 判断是否传入类型
    if (type == '') {
        where = '';
    }
    console.log(where)
    db.query('SELECT *FROM zq_article ' + where + ' ORDER BY post_time DESC', function(err, data) {
        if (err) {
            console.log(err);
            res.status(500).send('database error').end();
        } else {
            res.json(data);
        }
    })
})

router.post('/post', function(req, res, next) {
    var type = req.body.type || '';
    var page = req.body.page || 1;
    var where = ' WHERE category="' + type + '"'; //查询条件
    console.log(req.body)
    // 判断是否传入类型
    if (type == '') {
        where = '';
    }
    console.log(where)
    db.query('SELECT *FROM zq_article ' + where + ' ORDER BY post_time DESC', function(err, data) {
        if (err) {
            console.log(err);
            res.status(500).send('database error').end();
        } else {
            res.json(data);
        }
    })
})


module.exports = router